/*************************************************************************
> File Name: 02_test.cpp
> Author: hzy
> Created Time: 2023-08-16 11:20:17
> Description: 类模板
************************************************************************/
#include <iostream>

using namespace std;

template <class T>
class Base
{
private:
    T Val;

public:
    Base(T myVal) : Val(myVal) {}

    // 类型转化构造函数
    template <class U>
    explicit Base(Base<U> &other)
    {
        this->Val = static_cast<T>(other.getVal());
    }

    void setVal(T myVal)
    {
        Val = myVal;
    }

    T getVal();
};

/* 类模板成员函数在类外部定义实现 */
template <class T>
T Base<T>::getVal()
{
    return this->Val;
}

// 测试类型转化构造函数是否成功，int -> char,  int -> double
void test_01()
{
    Base<int> base_int(6);
    cout << base_int.getVal() << endl;
    base_int.setVal(97);
    cout << base_int.getVal() << endl;

    // 将base_int对象传给base_char对象，调用类型转换构造函数
    Base<char> base_char(base_int);
    cout << base_char.getVal() << endl;

    // 将base_int对象传给base_double对象，调用类型转换构造函数
    Base<double> base_double(base_int);
    cout << base_double.getVal() << endl;
}

// 测试类型转化构造函数是否成功 float -> int
void test_02()
{
    Base<float> base_float(97.5);
    cout << base_float.getVal() << endl;

    //将base_float对象传给base_int对象，调用类型转换构造函数
    Base<int> base_int(base_float);
    cout << base_int.getVal() << endl;
}

// 测试getVal()和setVal()方法是否成功
void test_03()
{
    Base<string> base_string("qaqaqaq");
    cout << base_string.getVal() << endl;
    base_string.setVal("cvcvcvcv");
    cout << base_string.getVal() << endl;
}

int main()
{
    test_01();
    cout << "=====================" << endl;
    test_02();
    cout << "=====================" << endl;
    test_03();

    return 0;
}